package com.wan.data.mysql.orm.entity;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wan.data.mysql.orm.convert.Converter;
import com.wan.data.mysql.orm.meta.ColumnMeta;
import com.wan.data.mysql.orm.meta.MetaUtil;
import com.wan.data.mysql.orm.meta.TableMeta;
import com.wan.util.cglib.FastClassUtil;

import java.sql.ResultSet;

public class EntityWrapper {

    private static final Log log = LogFactory.get();

    @SuppressWarnings("unchecked")
    public static  <T extends Entity<?>>T wrap(TableMeta tableMeta, ResultSet resultSet){
        try {
            Object instance = FastClassUtil.newInstance(tableMeta.getEntityType());
            for (ColumnMeta columnMeta : tableMeta.getColumnMetas()) {
                Converter converter = Converter.get(columnMeta);
                Object object = resultSet.getObject(columnMeta.getColumnName());
                if(object != null){
                    object = converter.dbToEntity(columnMeta, object);
                }
                columnMeta.getFastField().set(instance,object);
            }
            T t = (T) instance;
            t.afterInit();
            return t;
        } catch (Exception e) {
            log.error(e,"实体{}包装失败",tableMeta.getEntityType().getName());
            return null;
        }
    }

    public static <T extends Entity<?>> Object[] unWrap(T t,boolean containAuto){
        TableMeta tableMeta = MetaUtil.getTableMeta(t.getClass());
        ColumnMeta[] operateColumns = tableMeta.getOperateColumns(containAuto);
        Object[] objects = new Object[operateColumns.length];
        try {
            for (int i = 0; i < operateColumns.length; i++) {
                ColumnMeta columnMeta = operateColumns[i];
                Object o = columnMeta.getFastField().get(t);
                if(o != null){
                    Converter converter = Converter.get(columnMeta);
                    o = converter.entityToDb(columnMeta,o);
                }
                objects[i] = o;
            }
        } catch (Exception e) {
            log.error(e,"实体{}拆包失败",tableMeta.getEntityType().getName());
        }
        return objects;
    }

    public static <T extends Entity<?>> Object[] unWrap(T t){
        return unWrap(t,false);
    }




}
